
#import "SceneBatteryView.h"
#import "SceneMenu.h"
#import "SceneGameOver.h"
#import "global.h"
#import "OpenFeint.h"
#import "OFHighScoreService.h"


@implementation BatteryView

@synthesize spBackground, spHitEffect, spHitCombo, blnSwing;

+(id) scene
{	
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	BatteryView *layer = [BatteryView node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if ( (self=[super init] )) 
	{
		m_windowSize = [[CCDirector sharedDirector] winSize];
		
		if ( m_windowSize.width == 768 )
			m_DeviceKind = DEVICE_IPAD;
		else
			m_DeviceKind = DEVICE_IPHONE;
		
		//game info
		gameInfo.nScore = 0;
		gameInfo.nBallCnt = 0;
		
		//bg image
		spBackground = [CCSprite spriteWithFile:@"background2.png"];
		[spBackground setPosition:ccp(BG_START_X,BG_START_Y)];
		[self addChild:spBackground];
		
		//score
		NSString *strCurrentScore = [NSString stringWithFormat:@"Score: %d", gameInfo.nScore];
		labelScore = [CCLabel labelWithString:strCurrentScore fontName:@"MarkerFelt-Thin" fontSize:18];
		[self addChild: labelScore];
		[labelScore setColor:ccc3(255,255,255)];
		[labelScore setPosition: ccp(50, 20)];
		
		//left chance
		gameInfo.nLeftChance = MAX_LEFT_CHANCE;
		arrayChance = [[NSMutableArray alloc] init];
		[self initChance];
		
		//combo count
		gameInfo.nComboCnt = 0;
				
		//currentBall
		currentBall = [[ball alloc] init];
	
		currentBall.spBall = [CCSprite spriteWithFile: @"ball.png"];
		[currentBall.spBall setPosition: ccp([currentBall GetX:0], [currentBall GetY:0])];
		[currentBall.spBall setScale:0.1f];
		[self addChild:currentBall.spBall z:0];
	
		currentBall.spBallShadow = [CCSprite spriteWithFile: @"ball_shadow.png"];
		[currentBall.spBallShadow setPosition: ccp([currentBall GetX:0], [currentBall GetShadowY:0])];
		[currentBall.spBallShadow setScale:0.1f];
		[self addChild:currentBall.spBallShadow z:0];
		
		//currentBatter
		currentBatter = [[batter alloc] init];
		[self addChild:currentBatter.spBatterReady];
		[self addChild:currentBatter.spBatterSwing];
		[currentBatter.spBatterSwing setVisible: FALSE];
		[currentBatter.spBatterReady runAction:[CCRepeatForever actionWithAction: currentBatter.aniBatterReady]];

		//currentPS
		currentPS = [[PitchingSystem alloc] init];
		[currentPS SetCurrentPitchingSystem: PS_PITCHING_INTERVAL];
		
		//hit effect
		spHitEffect = [CCSprite spriteWithFile:@"goodshot.png"];
		[spHitEffect setPosition:ccp(CX,CY)];
		[self addChild:spHitEffect];
		[spHitEffect setVisible:FALSE];
		
		//combo effect
		spHitCombo = [CCSprite spriteWithFile:@"combo.png"];
		[spHitCombo setPosition:ccp(CX,CY)];
		[self addChild:spHitCombo];
		[spHitCombo setVisible:FALSE];
		
		//sound
		[self initShortSound];
		[self initLongSound];
		[player setNumberOfLoops: -1];
		[player play];
		
		//etc
		self.blnSwing = FALSE;
		
		glLineWidth(2);
		glColor4ub(0, 255, 255, 255);
		ccDrawCircle( ccp(CX,CY), 50, CC_DEGREES_TO_RADIANS(90), 50, YES);
		
		[self schedule:@selector(step:) interval:1.0/60];
		isTouchEnabled = YES;
	}
	return self;
}

- (void)initShortSound 
{
	NSString *path;
	NSURL *url;
	
	path = [[NSBundle mainBundle] pathForResource:@"hit_bad" ofType:@"wav"];
	url = [NSURL fileURLWithPath:path];
	AudioServicesCreateSystemSoundID ((CFURLRef)url, &sndHitBad);
	
	path = [[NSBundle mainBundle] pathForResource:@"hit_good" ofType:@"wav"];
	url = [NSURL fileURLWithPath:path];
	AudioServicesCreateSystemSoundID ((CFURLRef)url, &sndHitGood);
	
	path = [[NSBundle mainBundle] pathForResource:@"mitt" ofType:@"wav"];
	url = [NSURL fileURLWithPath:path];
	AudioServicesCreateSystemSoundID ((CFURLRef)url, &sndMitt);
}

- (void)initLongSound 
{
	if (!player) {
		NSString *path = [[NSBundle mainBundle] pathForResource:@"bgm_game" ofType:@"mp3"];
		NSURL *url = [NSURL fileURLWithPath:path];
		
		player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
	}	
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	
	[currentBall release];
	[currentPS release];
	
	[currentBatter.spBatterReady release];
	[currentBatter.aniBatterReady release];
	[currentBatter.spBatterSwing release];
	[currentBatter.aniBatterSwing release];
	[currentBatter release];
	
	[arrayChance release];

	[player stop];
	[player release];
	
	[self unschedule:@selector(step:)];
	
	[super dealloc];
}

-(void) step:(ccTime)dt
{
	int nX, nY, nShadowY, nBGPosX, nBGPosY;
	float nScale;
	
	switch ( currentPS.nState )
	{
		case PS_PITCHING_INTERVAL :
			if ( currentPS.nFrame < 30 )
				currentPS.nFrame++;
			else
				[currentPS SetCurrentPitchingSystem: PS_PITCHING_BALL_FLY];
			break;
			
		case PS_PITCHING_BALL_FLY :
			nX = [currentBall GetX:currentBall.nCurrentFrame];
			nY = [currentBall GetY:currentBall.nCurrentFrame];
			nShadowY = [currentBall GetShadowY:currentBall.nCurrentFrame];
				nScale = [currentBall GetSize:currentBall.nCurrentFrame];
			
			[currentBall.spBall setPosition: ccp(nX,nY)];
			[currentBall.spBall setScale: nScale];
			[currentBall.spBallShadow setPosition: ccp(nX,nShadowY)];
			[currentBall.spBallShadow setScale: nScale];
			
			self.blnSwing = FALSE;
			
			if ( currentBall.nCurrentFrame < currentBall.nTotalFrame + EXTRA_FRAME - 1 )
				currentBall.nCurrentFrame++;
			else
			{
				[currentPS SetCurrentPitchingSystem: PS_MITT_DELAY];
				gameInfo.nLeftChance--;
				[self updateChance];
				
				AudioServicesPlaySystemSound(sndMitt);
			}
			break;
			
		case PS_BATTING_BALL_FLY :
			if ( currentBall.nCurrentFrame < MAX_FRAME_HITTING_BALL + 10 )
			{
				if ( currentBall.nCurrentFrame < MAX_FRAME_HITTING_BALL - 1 )
				{
					nX = [currentBall GetX:currentBall.nCurrentFrame];
					nY = [currentBall GetY:currentBall.nCurrentFrame];
					nShadowY = [currentBall GetShadowY:currentBall.nCurrentFrame];
					nScale = [currentBall GetSize:currentBall.nCurrentFrame];
					
					[currentBall.spBall setPosition: ccp(nX,nY)];
					[currentBall.spBall setScale: nScale];
					[currentBall.spBallShadow setPosition: ccp(nX,nShadowY)];
					[currentBall.spBallShadow setScale: nScale];
					
					//move bg
					if ( m_DeviceKind == DEVICE_IPHONE )
					{
						nBGPosX = BG_START_X+([currentBall GetX:0]-nX);
						if ( [currentBall GetX:0] < nX )
							nBGPosX = MAX(-280,nBGPosX);
						else
							nBGPosX = MIN(280,nBGPosX);
						
						nBGPosY = BG_START_Y+([currentBall GetY:0]-nY);
						nBGPosY = MAX(BG_START_Y-290,nBGPosY);
						
						[spBackground setPosition:ccp(nBGPosX, nBGPosY)];
					}
					else
					{
						
					}
					
					//stay bat
					if ( m_DeviceKind == DEVICE_IPHONE )
						[currentBatter.spBatterSwing setPosition: ccp(BAT_START_X+([currentBall GetX:0]-nX), BAT_START_Y+([currentBall GetY:0]-nY))];;
					
					//hit effect
					if ( currentBall.nCurrentFrame == 10 )
					{
						[spHitEffect setVisible:FALSE];
						[spHitCombo setVisible:FALSE];
					}
				}
				currentBall.nCurrentFrame++;
			}
			else
			{
				[currentBall init];
				[currentPS SetCurrentPitchingSystem: PS_PITCHING_INTERVAL];
				
				[currentBatter.spBatterSwing setVisible: FALSE];
				[currentBatter.spBatterReady setVisible: TRUE];
				
				[spBackground setPosition:ccp(BG_START_X,BG_START_Y)];
				[currentBatter.spBatterSwing setPosition: ccp(BAT_START_X, BAT_START_Y-30)];
				
				//score
				if ( hitInfo.blnHitTimingGood )
					gameInfo.nScore += (10*gameInfo.nComboCnt);
				else
					gameInfo.nScore += 1;				
				NSString *strNewPoint = [NSString stringWithFormat:@"Score: %d", gameInfo.nScore];	
				[labelScore setString: strNewPoint];
			}
			break;
			
		case PS_MITT_DELAY :
			if ( currentPS.nFrame < 30 )
				currentPS.nFrame++;
			else
			{
				if ( gameInfo.nLeftChance <= 0 )
				{
					if ( gameInfo.blnPracticeMode )
					{
						Menu *ms = [Menu node];
						[[CCDirector sharedDirector] replaceScene: (CCScene*)ms];
					}
					else
					{
						//openfeint
						[OFHighScoreService setHighScore:gameInfo.nScore forLeaderboard:@"448694" onSuccess:OFDelegate() onFailure:OFDelegate()];
						
						GameOver *os = [GameOver node];
						[[CCDirector sharedDirector] replaceScene: (CCScene*)os];
					}
				}
				else
				{
					[currentBall init];
					[currentPS SetCurrentPitchingSystem: PS_PITCHING_INTERVAL];
					
					[currentBatter.spBatterSwing setVisible: FALSE];
					[currentBatter.spBatterReady setVisible: TRUE];
				}
			}
			break;
	}
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSLog(@">> ccTouchesEnded #1 - %d", blnSwing);
	
	if ( currentPS.nState == PS_PITCHING_BALL_FLY || currentPS.nState == PS_MITT_DELAY )
	{
		if ( self.blnSwing == FALSE )
		{
			self.blnSwing = TRUE;
			NSLog(@">> ccTouchesEnded #2 - %d", blnSwing);
			
			[currentBatter.spBatterReady setVisible: FALSE];
			[currentBatter.spBatterSwing setVisible: TRUE];
			[currentBatter.spBatterSwing stopAllActions];
			[currentBatter.spBatterSwing runAction: currentBatter.aniBatterSwing];
				
			if ( currentBall.nCurrentFrame >= currentBall.nTotalFrame-EXTRA_FRAME-HIT_TIMING_FAST && 
				 currentBall.nCurrentFrame <= currentBall.nTotalFrame-EXTRA_FRAME-HIT_TIMING_SLOW )
			{	
				[currentPS SetCurrentPitchingSystem: PS_BATTING_BALL_FLY];
				if ( currentBall.nCurrentFrame >= currentBall.nTotalFrame-EXTRA_FRAME &&
					 currentBall.nCurrentFrame <= currentBall.nTotalFrame-EXTRA_FRAME+1 )
				{
					NSLog(@">> Hit timing good!!");
					hitInfo.blnHitTimingGood = TRUE;
					gameInfo.nComboCnt++;
					AudioServicesPlaySystemSound(sndHitGood);
					
					if ( gameInfo.nComboCnt >= 2 )
					{
						[spHitEffect setPosition:ccp([currentBall GetX:currentBall.nCurrentFrame],[currentBall GetY:currentBall.nCurrentFrame])];
						[spHitCombo setVisible:TRUE];
					}
					else
					{
						[spHitEffect setPosition:ccp([currentBall GetX:currentBall.nCurrentFrame],[currentBall GetY:currentBall.nCurrentFrame])];
						[spHitEffect setVisible:TRUE];
					}
				}
				else
				{
					hitInfo.blnHitTimingGood = FALSE;
					gameInfo.nComboCnt = 0;
					AudioServicesPlaySystemSound(sndHitBad);
				}
				
				[currentBall GenerateBatteryViewBattingBall];
			}
		}
	}
}

- (void)initChance
{	
	for ( int i=0; i<gameInfo.nLeftChance; i++ )
	{
		CCSprite *spLeftBall = [CCSprite spriteWithFile:@"ball.png"];
		[arrayChance addObject:spLeftBall];
	}
	
	int j=0;
	for ( CCSprite *spLeftBall in arrayChance )
	{
		[spLeftBall setScale:0.5f];
		[spLeftBall setPosition: ccp((SCREEN_WIDTH-17)-(20*j), 18)];
        [self addChild: spLeftBall];
		j++;
	}
}

- (void)updateChance
{
	for ( CCSprite *spLeftBall in arrayChance )
	{
		[self removeChild:spLeftBall cleanup:TRUE];
	}
	[arrayChance release];
	arrayChance = [[NSMutableArray alloc] init];
	[self initChance];
}

@end




















